/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.crystalrange.documents.web;

import org.crystalrange.BaseController;
import org.crystalrange.Message;
import org.crystalrange.documents.model.DocumentCategory;
import org.crystalrange.documents.service.DocumentCategoryService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.util.Clients;

/**
 *
 * @author Krzysiek
 */
public class DocumentCategoryController extends BaseController {
    
    private DocumentCategory documentCategory;
    private DocumentCategoryService documentCategoryService;

    public DocumentCategory getDocumentCategory() {
        return documentCategory;
    }

    public void setDocumentCategory(DocumentCategory documentCategory) {
        this.documentCategory = documentCategory;
    }

    public DocumentCategoryService getDocumentCategoryService() {
        return documentCategoryService;
    }

    public void setDocumentCategoryService(DocumentCategoryService documentCategoryService) {
        this.documentCategoryService = documentCategoryService;
    }
    
    public void onClick$toolbarbuttonDocumentCategorySave(Event event) throws Exception {
        this.documentCategorySave();
    }
    
    public void onClick$menuitemDocumentCategorySave(Event event) throws Exception {
        this.documentCategorySave();        
    } 
    
    private void documentCategorySave() throws Exception {
    	if (this.documentCategory.getName() != null) {
			this.documentCategoryService.save(this.documentCategory);
			this.sessionScope.put("CRYSTALRANGE_MESSAGE", new Message("Saved successfully!"));
			Clients.evalJavaScript("window.history.back();");
		} else {
			this.message.setText("You must enter 'Category Name'.");
            this.message.setIcon("/img/exclamation.png");
            this.binder.loadAll();
		}
    }
    
    @Override
    public void doAfterCompose(Component component) throws Exception {
        super.doAfterCompose(component);
        
        if (this.execution.getParameter("Id") != null) {
            this.documentCategory = this.documentCategoryService.find(
                    Long.parseLong(this.execution.getParameter("Id")));
            this.labelTitle.setValue("Edit Document Category");
        } else {
            this.documentCategory = this.documentCategoryService.create(
                    SecurityContextHolder.getContext().getAuthentication().getName());
            this.labelTitle.setValue("Create Document Category");
        }
        
        component.setAttribute("controller", this);
    }
}
